import React, { PureComponent } from 'react';
import { DATA_ENTRY, AdvancedSearch, PrimaryC, NoQueryC, exportPDF, ContentPackage } from '../../../comps';

import { connect } from 'dva';
import { message } from 'antd';
import moment from 'moment';
import NonStandardBond from './nonStandardBond';
import ConcentrationManagement from './concentrationManagement';
import LeverControl from './leverControl';
import LiquidityRiskControl from './liquidityRiskControl';
import Introduction from './Introduction';
import styles from './style.less';

@connect(({ commercialBankReportM, globalM }) => ({
  commercialBankReportM,
  globalM,
}))
export default class commercialBankManagementReport extends PureComponent {
  state = {
    searchData: null,
    tradingDate: null,
    exportLoading: false,
    isfirst: true,
    ref: null,
  };
  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { BAXX_CPYZMS = [] },
      },
    } = this.props;
    this.props.dispatch({
      type: 'commercialBankReportM/save',
      payload: {
        openModeList: BAXX_CPYZMS,
      },
    });
    this.props.dispatch({
      type: 'commercialBankReportM/getTradingDate',
      payload: { type: '1' },
      callback: (res) => {
        this.setState({
          tradingDate: res,
        });
      },
    });
  }

  componentDidUpdate(prevProps, prevState) {}
  //判断页面是否有缩放(返回100代表没有缩放)
  detectZoom = () => {
    var ratio = 0,
      screen = window.screen,
      ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('Mac OS X') || ua.indexOf('Mac')) {
      ratio = window.outerWidth / window.innerWidth;
    } else {
      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else {
        if (~ua.indexOf('msie')) {
          if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
          }
        } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
          ratio = window.outerWidth / window.innerWidth;
        }
      }
    }
    if (ratio) {
      ratio = Math.round(ratio * 100);
    }
    return ratio;
  };
  //判断是否为360浏览器
  is360Chrome = () => {
    const uas = navigator.userAgent.split(' ');
    let result = false;
    // 排除ua自带标志的双核浏览器, 余下chrome, chromium及360浏览器
    if (uas[uas.length - 1].indexOf('Safari') == -1) {
      return result;
    }
    for (const key in navigator.plugins) {
      if (!Object.prototype.hasOwnProperty.call(navigator.plugins, key)) {
        continue;
      }
      // np-mswmp.dll文件在chromium及chrome未查询到
      if (navigator.plugins[key].filename === 'np-mswmp.dll') {
        return true;
      }
    }
    return result;
  };

  onExportpdf = () => {
    //检查页面是否有缩放，若有，则禁止导出
    if (this.is360Chrome()) {
      //360浏览器特殊处理
      if (!(Math.abs(this.detectZoom() - 100) < 5)) {
        // 去除loading状态
        this.props?.onDownloading && this.props.onDownloading(false);
        this.setState({
          start: false,
        });
        message.warning('请将页面缩放比例设置为100%后再进行导出！');
        return;
      }
    } else if (this.detectZoom() !== 100) {
      // 去除loading状态
      this.props?.onDownloading && this.props.onDownloading(false);
      this.setState({
        start: false,
      });
      message.warning('请将页面缩放比例设置为100%后再进行导出！');
      return;
    }

    //关闭流动性风险子表格
    this.state.ref?.onClearExpandedRowKeys();

    this.setState({ exportLoading: true });
    const pdf = new exportPDF();
    pdf.savePDF('syyhexportpdfid', 'syyh-pdf', `商业银行管理报告-${moment().format('YYYY-MM-DD')}`, () => {
      this.setState({ exportLoading: false });
    });
  };

  render() {
    const { searchData, date, tradingDate } = this.state;

    const searchProps = {
      dataSource: [
        {
          type: DATA_ENTRY.SINGLEDATE,
          dataIndex: 'time',
          title: '日期',
          allowClear: false,
          initialValue: moment(tradingDate),
        },
      ],
      onQuery: (e) => {
        this.setState({
          searchData: {
            date: moment(e.time).format('YYYYMMDD'),
          },
          isfirst: false,
        });
      },
      onClear: () => {},
    };

    return (
      <ContentPackage
        title='商业银行管理报告'
        contentHtml={
          <div className='commercialBankManagementReport' style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC title='导出' disabled={this.state.isfirst} loading={this.state.exportLoading} onClick={() => this.onExportpdf()} style={{ margin: '20px 0' }}></PrimaryC>

            {searchData ? (
              <div className={styles.wrapperLine}>
                {/* 添加 className='exportpdfreport' 引用table.less 里的样式解决表头最后一列导出无背景色的问题（需添加一个空列） */}
                <div id='syyhexportpdfid' className='exportpdfreport' style={{ width: '1301px', margin: '0 auto', paddingBottom: ' 20px' }}>
                  {/* 标题 */}
                  <Introduction searchData={searchData}></Introduction>
                  <NonStandardBond searchData={searchData}></NonStandardBond>
                  <ConcentrationManagement searchData={searchData} />
                  <LeverControl searchData={searchData} />
                  <LiquidityRiskControl searchData={searchData} onRef={(e) => this.setState({ ref: e })} />
                </div>
              </div>
            ) : (
              <div style={{ marginTop: '20px' }}>
                <NoQueryC></NoQueryC>
              </div>
            )}
          </div>
        }
      />
    );
  }
}
